package com.gemme.gemme.manager;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.login.LoginNewActivity;
import com.gemme.gemme.login.UseInfoBean;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Authenticator;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;

/**
 * Created by sp on 2019/10/21.
 */
public class DataManager {

  /*  public static final String BaseUrl = "http://192.168.1.5"; //大哥的环境
    public static final String BaseUrl_panghu = "http://192.168.1.4"; //胖虎的环境
    public static final String BaseUrl_weicheng = "http://192.168.1.9"; //赵围城的环境
    public static final String BaseUrl_yanglinyu = "http://192.168.1.6"; //杨林宇
*/
  public static final String Duankou = ":9999/";
//  public static final String Duankou = "";
    public static final String BaseUrl = "http://47.114.162.17:9999/";//5
//    public static final String BaseUrl = "http://192.168.1.4" + Duankou;//5
    public static final String BaseUrl_panghu = BaseUrl;
    public static final String BaseUrl_weicheng = BaseUrl;
    public static final String BaseUrl_yanglinyu = BaseUrl;



    public static final String BaseUrl_jinlong = BaseUrl; //金龙的环境
//    public static final String BaseUrl_jinlongnew = "http://192.168.1.8"; //金龙的环境
    public static final String AuthorizationKey = "Authorization"; //固定值
    public static final String Authorization = "Basic bW9iaWxlOm1vYmlsZQ=="; //固定值
    public static final String token = "Bearer 0135c8bf-6b2d-4ac4-aad8-0977fdeb47d4";


    public static String getToken(Context context){
        String token_1 = "";
        try {

            SharedPreferences MSP = context.getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
            String trim_token = MSP.getString(Constant.ACCESS_TOKEN, "").trim();
            String access_token = "Bearer "+ MSP.getString(Constant.ACCESS_TOKEN, "").trim();
            if (!TextUtils.isEmpty(trim_token)){
                token_1 = access_token;
            }else{
                token_1 = token;
            }

        }catch (Exception e){

        }
        return token_1;
    }

    public static final String FAILRESPONSE = "-1";
    public static void postDataToServer(final Context context, String url, String json, final GeResponse geResponse){
        if(context == null || url == null || json == null || geResponse == null)
            return;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder().post(body).url(url).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("");
                backMainThread(context,FAILRESPONSE,geResponse);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                backMainThread(context,str,geResponse);
                System.out.println("");
            }
        });
    }

    public static void postDataToServerByHeader(final Context context, String url, String json,
                                                HashMap<String,String> headMap, final GeResponse geResponse){
        if(context == null || url == null || json == null || geResponse == null)
            return;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request;
        Request.Builder builder;
        if(headMap != null){
            builder = new Request.Builder().post(body).url(url);

            for (String key : headMap.keySet()) {
                System.out.println(key + "=" + headMap.get(key));
                builder.addHeader(key,headMap.get(key));
            }

            request = builder.
                    build();
        }else{
            request = new Request.Builder().post(body).url(url).
                    build();
        }




        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("");
                backMainThread(context,FAILRESPONSE,geResponse);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                backMainThread(context,str,geResponse);
                System.out.println("");
            }
        });
    }


    public static void putDataToServer(final Context context, String url, String json, final GeResponse geResponse){
        if(context == null || url == null || json == null || geResponse == null)
            return;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder().put(body).url(url).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("");
                backMainThread(context,FAILRESPONSE,geResponse);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                backMainThread(context,str,geResponse);
                System.out.println("");
            }
        });
    }

    //异步操作
    public static void getDataFromServer(final Context context, String url, final GeResponse geResponse){
        if(context == null || url == null || geResponse == null)
            return;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            final Request request = new Request.Builder()
                    .url(url)
                    .get()//默认就是GET请求，可以不写
                    .build();
            Call call = okHttpClient.newCall(request);


            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回到主线程
                    backMainThread(context,FAILRESPONSE,geResponse);
                    System.out.println();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    backMainThread(context,str,geResponse);
                    System.out.println("");
                }
            });
        }catch (Exception e){

        }
    }

    //同步get操作
    public static String getDataExecute(String url){
        String data = "";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        final Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            data = response.body().string();
            return data;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return data;
    }


    //异步操作
    public static void deleteData(final Context context, String url, final GeResponse geResponse){
        if(context == null || url == null || geResponse == null)
            return;
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            final Request request = new Request.Builder()
                    .url(url)
                    .delete()//默认就是GET请求，可以不写
                    .build();
            Call call = okHttpClient.newCall(request);


            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回到主线程
                    backMainThread(context,FAILRESPONSE,geResponse);
                    System.out.println();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    backMainThread(context,str,geResponse);
                    System.out.println("");
                }
            });
        }catch (Exception e){

        }
    }

    private static void backMainThread(final Context context, final String s, final GeResponse response) {
        if(s == null || response == null)
            return;

        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if(FAILRESPONSE.equals(s)){
//                    ToastUtil.setToast(context,"请求失败");
                }
                response.onResponse(s);
            }
        });
    }

    public interface GeResponse{
        void onResponse(String response);
    }


    //异步支持get和post
    public static void toServer(final Context context, String url, boolean isget,String json,
                                                HashMap<String,String> headMap, final GeResponse geResponse){
        if(context == null || url == null || json == null || geResponse == null)
            return;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request;
        Request.Builder builder;
        if(isget){
            builder =  new Request.Builder()
                    .url(url)
                    .get();
        }else{

            builder = new Request.Builder().post(body).url(url);
        }
        if(headMap != null){
            for (String key : headMap.keySet()) {
                System.out.println(key + "=" + headMap.get(key));
                builder.addHeader(key,headMap.get(key));
            }
        }
        request = builder.build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("");
                backMainThread(context,FAILRESPONSE,geResponse);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                backMainThread(context,str,geResponse);
                System.out.println("");
            }
        });
    }

    //同步刷新token

    public static void refreshToken(Context context){
        try {
            SharedPreferences MSP = context.getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
            String ACCESS_TOKENTIME = MSP.getString(Constant.ACCESS_TOKENTIME, "").trim();
            String REFRESH_TOKEN = MSP.getString(Constant.REFRESH_TOKEN, "").trim();
            String ACCESS_TOKEN = MSP.getString(Constant.ACCESS_TOKEN, "").trim();
            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "");
            Request request;
            Request.Builder builder = null;
            String url = BaseUrl + "auth/oauth/token?"+
                    "refresh_token="+ REFRESH_TOKEN
                    +"&scope=server&grant_type=refresh_token";
            builder = new Request.Builder().post(body).url(url);
            builder.addHeader(DataManager.AuthorizationKey,"Basic bW9iaWxlOm1vYmlsZQ==");
            request = builder.build();
            Call call = okHttpClient.newCall(request);
            Response res = call.execute();
            String response = res.body().string();
            UseInfoBean useInfos = JSON.parseObject(response,UseInfoBean.class);
            if(!TextUtils.isEmpty(useInfos.getAccess_token()))
                MSP.edit().putString(Constant.ACCESS_TOKEN, useInfos.getAccess_token()).apply();
            if(!TextUtils.isEmpty(useInfos.getRefresh_token()))
                MSP.edit().putString(Constant.REFRESH_TOKEN, useInfos.getRefresh_token()).apply();
            if(!TextUtils.isEmpty(useInfos.getUser_info().getId()))
                MSP.edit().putString(Constant.UserId, useInfos.getUser_info().getId() + "").apply();
            MSP.edit().putString(Constant.ACCESS_TOKENTIME, System.currentTimeMillis() + "").apply();
            MSP.edit().putString(Constant.REFRESH_TIME, System.currentTimeMillis() + "").apply();
        }catch (Exception e){

        }

    }

    //判断token是否过期
    private static void judgeToken(Context context) {
      try {
          SharedPreferences MSP = context.getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
          String ACCESS_TOKENTIME = MSP.getString(Constant.ACCESS_TOKENTIME, "").trim();
          String REFRESH_TOKEN = MSP.getString(Constant.REFRESH_TOKEN, "").trim();
          String ACCESS_TOKEN = MSP.getString(Constant.ACCESS_TOKEN, "").trim();
          if(TextUtils.isEmpty(ACCESS_TOKENTIME) || TextUtils.isEmpty(REFRESH_TOKEN)
                  || TextUtils.isEmpty(ACCESS_TOKEN)){
              return;
          }
           Long diff_time =  System.currentTimeMillis() - Long.parseLong(ACCESS_TOKENTIME);
           if( Math.abs(diff_time ) < 10 * 60 * 60 * 1000){//定义十小时刷新
                return;
            }

           refreshToken(context);

/*          OkHttpClient okHttpClient = new OkHttpClient();
          RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "");
          Request request;
          Request.Builder builder = null;
          String url = BaseUrl + ":9999/auth/oauth/token?"+
                  "refresh_token="+ REFRESH_TOKEN
                  +"&scope=server&grant_type=refresh_token";
          builder = new Request.Builder().post(body).url(url);
          builder.addHeader(DataManager.AuthorizationKey,"Basic bW9iaWxlOm1vYmlsZQ==");
          request = builder.build();
          Call call = okHttpClient.newCall(request);
          call.enqueue(new Callback() {
              @Override
              public void onFailure(Call call, IOException e) {
                  System.out.println("");
//                  backMainThread(context,FAILRESPONSE,geResponse);
              }

              @Override
              public void onResponse(Call call, Response response) throws IOException {
                  String str = response.body().string();
//                  backMainThread(context,str,geResponse);
                  System.out.println("");

                  try {
                      UseInfoBean useInfos = JSON.parseObject(str,UseInfoBean.class);
                      if(!TextUtils.isEmpty(useInfos.getAccess_token()))
                      MSP.edit().putString(Constant.ACCESS_TOKEN, useInfos.getAccess_token()).apply();
                      if(!TextUtils.isEmpty(useInfos.getRefresh_token()))
                      MSP.edit().putString(Constant.REFRESH_TOKEN, useInfos.getRefresh_token()).apply();
                      if(!TextUtils.isEmpty(useInfos.getUser_info().getId()))
                      MSP.edit().putString(Constant.UserId, useInfos.getUser_info().getId() + "").apply();
                      MSP.edit().putString(Constant.ACCESS_TOKENTIME, System.currentTimeMillis() + "").apply();
                      MSP.edit().putString(Constant.REFRESH_TIME, System.currentTimeMillis() + "").apply();
                  }catch (Exception e){

                  }

              }
          });*/
      }catch (Exception e){

      }
    }

    public static final int GET_TYPE = 0;
    public static final int POST_TYPE = 1;
    public static final int DELETE_TYPE = 2;
    public static final int PUT_TYPE = 3;

    //异步支持get和post 和delete,带刷新token
    public static void toServer2(final Context context, String url, int type,String json,
                                HashMap<String,String> headMap, final GeResponse geResponse){
//        todo 暂时刷新token去除,后期优化
//        judgeToken(context);
        if(context == null || url == null || json == null || geResponse == null)
            return;
//        OkHttpClient okHttpClient = new OkHttpClient();
        OkHttpClient okHttpClient = getOkhttp(context);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request;
        Request.Builder builder = null;
        if(type == GET_TYPE){
            builder =  new Request.Builder()
                    .url(url)
                    .get();
        }else if(type == POST_TYPE){

            builder = new Request.Builder().post(body).url(url);
        }else if(type == DELETE_TYPE){ //删除
            builder = new Request.Builder()
                    .url(url)
                    .delete();
        }else if(type == PUT_TYPE){
            builder = new Request.Builder()
                    .put(body)
                    .url(url);
        }


        if(headMap != null){
            for (String key : headMap.keySet()) {
                System.out.println(key + "=" + headMap.get(key));
                builder.addHeader(key,headMap.get(key));
            }
        }
        request = builder.build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("");
                backMainThread(context,FAILRESPONSE,geResponse);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                backMainThread(context,str,geResponse);
                System.out.println("");
            }
        });
    }

    /* Uri.Builder builder = Uri.parse(DataManager.BaseUrl + ":9999/user/userapp/edituser?").buildUpon();
     builder.appendQueryParameter("headImgUrl", http_head_url);*/

    //不进行刷新token操作
    public static void toServer3(final Context context, String url, int type,String json,
                                 HashMap<String,String> headMap, final GeResponse geResponse){
//        judgeToken(context);
        if(context == null || url == null || json == null || geResponse == null)
            return;
//        OkHttpClient okHttpClient = new OkHttpClient();
        OkHttpClient okHttpClient = getOkhttp(context);
/*
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().connectTimeout(50000, TimeUnit.MILLISECONDS)
                .readTimeout(50000, TimeUnit.MILLISECONDS)
                .build();
*/

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request;
        Request.Builder builder = null;
        if(type == GET_TYPE){
            builder =  new Request.Builder()
                    .url(url)
                    .get();
        }else if(type == POST_TYPE){

            builder = new Request.Builder().post(body).url(url);
        }else{ //删除
            builder = new Request.Builder()
                    .url(url)
                    .delete();
        }


        if(headMap != null){
            for (String key : headMap.keySet()) {
                System.out.println(key + "=" + headMap.get(key));
                builder.addHeader(key,headMap.get(key));
            }
        }
        request = builder.build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("");
                backMainThread(context,FAILRESPONSE,geResponse);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                backMainThread(context,str,geResponse);
                System.out.println("");
            }
        });
    }

    public static OkHttpClient getOkhttp(Context context){
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
//                .addInterceptor(new TokenInterceptor())
                .authenticator(new Authenticator() {
                    @javax.annotation.Nullable
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        int code = response.code();
                        if(code == 401){//http401重新登录
//                            cleardata(context);
                            context.startActivity(new Intent(context, LoginNewActivity.class));
                        }
                        return null;
                    }
                })
                .build();

        return client;
    }


    private static void cleardata(Context context) {
        SharedPreferences MSP = context.getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
        MSP.edit().putString(Constant.ACCESS_TOKEN, "").apply();
        MSP.edit().putString(Constant.REFRESH_TOKEN, "").apply();
        MSP.edit().putString(Constant.ACCESS_TOKENTIME, "").apply();
    }

}
